package com.quectel.core.module.grid.service.impl;


import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.grid.dao.GridNoticeDao;
import com.quectel.core.module.grid.dto.GridNoticeDto;
import com.quectel.core.module.grid.dto.GridNoticeRelationDto;
import com.quectel.core.module.grid.entity.GridNoticeEntity;
import com.quectel.core.module.grid.service.GridNoticeRelationService;
import com.quectel.core.module.grid.service.GridNoticeService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/02/03 16:42
 */
@DubboService
public class GridNoticeServiceImpl implements GridNoticeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridNoticeServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> GRID_NOTICE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "GRID_NOTICE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<GridNoticeDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(GRID_NOTICE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private GridNoticeDao gridNoticeDao;
    @Autowired
    private GridNoticeRelationService gridNoticeRelationService;
    @Autowired
    private VillageService villageService;

    /**
     * save or update
     * 保存当前对象和相关联的地区
     *
     * @param gridNoticeDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(GridNoticeDto gridNoticeDto) {
        if (gridNoticeDto.getId() == null) {
            Long id = save(gridNoticeDto);
            gridNoticeDto.setId(id);
        } else {
            updateById(gridNoticeDto);
        }

        //删除关联关系
        gridNoticeRelationService.deleteByGridNoticeId(gridNoticeDto.getTenantId(), gridNoticeDto.getId());

        //更新关联关系
        if (CollectionUtils.isNotEmpty(gridNoticeDto.getRelationList())) {
            for (GridNoticeRelationDto gridNoticeRelationDto : gridNoticeDto.getRelationList()) {
                gridNoticeRelationDto.setTenantId(gridNoticeDto.getTenantId());
                gridNoticeRelationDto.setGridNoticeId(gridNoticeDto.getId());
                gridNoticeRelationService.save(gridNoticeRelationDto);
            }
        }
    }


    @Override
    public GridNoticeDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                GRID_NOTICE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public GridNoticeDto selectById(Long id) {
        GridNoticeEntity entity = gridNoticeDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, GridNoticeDto.class));
    }

    @Override
    public List<GridNoticeDto> queryList(Map<String, Object> params) {
        List<GridNoticeEntity> list = gridNoticeDao.queryList(params);
        List<GridNoticeDto> result = CopyUtils.copyList(list, GridNoticeDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<GridNoticeDto> queryListWithNoPadding(Map<String, Object> params) {
        List<GridNoticeEntity> list = gridNoticeDao.queryList(params);
        List<GridNoticeDto> result = CopyUtils.copyList(list, GridNoticeDto.class);
        result.forEach(this::paddingField);
        return result;
    }


    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属社区等
     *
     * @param dto
     * @return
     */
    private GridNoticeDto paddingField(GridNoticeDto dto) {
        if (dto != null) {
            //查询对应的关系列表
            List<GridNoticeRelationDto> gridNoticeRelationDtos = gridNoticeRelationService.queryByGridNoticeId(dto.getTenantId(), dto.getId());
            dto.setRelationList(gridNoticeRelationDtos);

            if (dto.getVillageId() != null) {
                VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
                if (villageDto != null) {
                    dto.setVillageName(villageDto.getName());
                }
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return gridNoticeDao.queryTotal(params);
    }

    @Override
    public Long save(GridNoticeDto dto) {
        GridNoticeEntity entity = CopyUtils.copyObj(dto, GridNoticeEntity.class);
        entity.setId(Snowflake.nextId());
        gridNoticeDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(GridNoticeDto dto) {
        GridNoticeEntity entity = CopyUtils.copyObj(dto, GridNoticeEntity.class);

        gridNoticeDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(GridNoticeDto dto) {
        GridNoticeEntity entity = CopyUtils.copyObj(dto, GridNoticeEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, gridNoticeDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));


        GridNoticeDto noticeDto = selectById(id);
        if (noticeDto != null) {
            gridNoticeRelationService.deleteByGridNoticeId(noticeDto.getTenantId(), id);
        }

        gridNoticeDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
